package com.zhouyong.dubboFramework.http;

import com.zhouyong.dubboFramework.pojo.Invocation;
import com.zhouyong.dubboFramework.register.LocalRegister;
import org.apache.commons.io.IOUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ObjectInputStream;
import java.lang.reflect.Method;

/**
 * servlet过滤方法
 *
 * @Author 99
 * @Date 2022/7/27 17:16
 * @Version 1.0
 */
public class HttpServletHandler {

    public static void handler(HttpServletRequest req, HttpServletResponse resp) {
        try {
            System.out.println("=======================请求被拦截=====================");
            // 拦截请求，获取消费端传递的参数
            Invocation invocation = (Invocation) new ObjectInputStream(req.getInputStream()).readObject();

            // 获取参数
            String interfaceClassName = invocation.getInterfaceClassName();
            String methodName = invocation.getMethodName();
            Class<?>[] paramTypeNames = invocation.getParamTypeNames();
            Object[] paramValues = invocation.getParamValues();

            // 反射调用请求
            Class<?> clazz = LocalRegister.getMap(interfaceClassName);
            Method method = clazz.getMethod(methodName, paramTypeNames);
            String result = (String) method.invoke(clazz.newInstance(), paramValues);

            IOUtils.write(result, resp.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
